
<script setup>import { ref, getCurrentInstance, computed, onUnmounted, onMounted } from 'vue'
import { showFailToast, showSuccessToast } from 'vant'
import 'vant/lib/toast/style';
import { useUserStore } from "../stores/user.js";
import router from "../router/router.js";

const userStore = useUserStore()
const phone = ref('')
const password = ref('')
const confirmPassword = ref('')
const code = ref()
const isCountingDown = ref(false) // 是否正在倒计时
const countdown = ref(60) // 倒计时秒数
let timer = null // 定时器

const { proxy } = getCurrentInstance()

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 验证手机号是否为11位
const isValidPhone = computed(() => {
  return phone.value && phone.value.length === 11
})

const countdownText = computed(() => {
  return isCountingDown.value ? `${countdown.value}秒后重新发送` : '发送验证码'
})

// 页面加载时检查是否需要自动填充手机号
onMounted(() => {
  // 如果URL中包含autoFill=true参数且用户已登录，则自动填充当前用户的手机号
  const urlParams = new URLSearchParams(window.location.search);
  const autoFill = urlParams.get('autoFill');

  if (autoFill === 'true' && userStore.userInfo && userStore.userInfo.phone) {
    phone.value = userStore.userInfo.phone;
  }
})

const sendCode = () => {
  if (!phone.value) {
    showFailToast('请输入手机号')
    return
  }

  // 验证手机号是否为11位
  if (!isValidPhone.value) {
    showFailToast('请输入正确的11位手机号')
    return
  }

  proxy.$axios.post('/user/sendCode', {
    phone: phone.value

  }).then(ServerData => {
    if (ServerData.data.code === 0) {
      showSuccessToast("验证码发送成功")
      console.log(ServerData.data.data)
      startCountdown()
    } else {
      showFailToast("验证码发送失败")
    }
  }).catch(error => {
    console.log("请求发生异常", error);
    showFailToast("验证码发送失败,请稍后重试");
  })
}

const resetPassword = () => {
  // 验证输入
  if (!phone.value) {
    showFailToast('请输入手机号')
    return
  }

  // 验证手机号是否为11位
  if (!isValidPhone.value) {
    showFailToast('请输入正确的11位手机号')
    return
  }

  if (!password.value) {
    showFailToast('请输入密码')
    return
  }
  if (password.value !== confirmPassword.value) {
    showFailToast('两次输入的密码不一致')
    return
  }
  if (!code.value) {
    showFailToast('请输入验证码')
    return
  }
  proxy.$axios.post('/user/resetPassword', {
    phone: phone.value,
    password: password.value,
    code: parseInt(code.value)
  }).then(ServerData => {
    if (ServerData.data.code === 0) {
      showSuccessToast("密码重置成功")
      showSuccessToast("一秒后跳转登录页面")
      setTimeout(() => {
        router.push('/login?loginType=password')
      }, 1000)
    } else {
      showFailToast("密码重置失败")
    }
  }).catch(error => {
    console.log("请求发生异常", error);
    showFailToast("密码重置失败,请稍后重试");
  })
}

// 开始倒计时
const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60

  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      stopCountdown()
    }
  }, 1000)
}

// 停止倒计时
const stopCountdown = () => {
  isCountingDown.value = false
  clearInterval(timer)
  timer = null
}

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<template>
  <div style="margin-top:20px;margin-bottom: 20px; display: flex; justify-content: center" >
    <van-icon name="arrow-left" @click="goBack" style="position: absolute; left: 20px; font-size: 24px;" />
    重置密码
  </div>
  <van-cell-group>
    <van-field v-model="phone" type="digit" label="手机号" placeholder="请输入手机号" />
    <van-field v-model="password" type="password" label="密码" placeholder="请输入密码" />
    <van-field v-model="confirmPassword" type="password" label="确认密码" placeholder="请输入确认密码" />
    <van-field v-model="code" type="digit" label="验证码" placeholder="请输入验证码">
      <template #button>
        <van-button
            size="small"
            type="primary"
            :disabled="isCountingDown"
            @click="sendCode">{{ countdownText }}</van-button>
      </template>
    </van-field>
  </van-cell-group>
  <div style="display: flex; justify-content: center">
    <van-button
        size="normal"
        type="primary"      style="border-radius: 20px; width: 260px"
        @click="resetPassword">
      重置密码
    </van-button>
  </div>
</template>

<style scoped>.header {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  padding: 0 16px;
}

.back-icon {
  position: absolute;
  left: 16px;
  font-size: 24px;
  color: #333;
}

h3 {
  margin: 0;
}
</style>